/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import com.bourre.data.libs.XMLToObject;
import com.bourre.data.libs.XMLToObjectDeserializer;

import fever.app.context.abstract.FileSystem;
import fever.app.context.abstract.IFileSystem;
import fever.commands.JSMethodName;
import fever.data.encoder.URLString;
import fever.log.FeverDebug;
import fever.utils.StringUtil;

import flash.external.ExternalInterface;

/**
 * Filesystem using server side technology ( + Ajax for synchron result )
 * 
 * @author Romain Ecarnot
 */
class fever.app.context.browser.HTTPFilesystem extends FileSystem  implements IFileSystem
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var _instance : HTTPFilesystem;
	private var _hasChanged : Boolean;
	private var _fileSystem : Object;
	private var _isAvailable : Boolean;
	
	
	//-------------------------------------------------------------------------
	// Public Properties
	//-------------------------------------------------------------------------
	
	public static var isDirectoryMETHOD : JSMethodName = new JSMethodName( 'isDirectory' );	public static var createDirectoryMETHOD : JSMethodName = new JSMethodName( 'createDirectory' );	public static var deleteDirectoryMETHOD : JSMethodName = new JSMethodName( 'deleteDirectory' );	public static var renameDirectoryMETHOD : JSMethodName = new JSMethodName( 'renameDirectory' );	public static var isFileMETHOD : JSMethodName = new JSMethodName( 'isFile' );	public static var deleteFileMETHOD : JSMethodName = new JSMethodName( 'deleteFile' );	public static var renameFileMETHOD : JSMethodName = new JSMethodName( 'renameFile' );	public static var writeToFileMETHOD : JSMethodName = new JSMethodName( 'writeToFile' );	public static var appendToFileMETHOD : JSMethodName = new JSMethodName( 'appendToFile' );	public static var readFileMETHOD : JSMethodName = new JSMethodName( 'readFile' );	public static var getContentMETHOD : JSMethodName = new JSMethodName( 'getContent' );
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns {@link LocalFilesystem} instance.
	 */
	public static function getInstance() : HTTPFilesystem
	{
		if( _instance == undefined ) _instance = new HTTPFilesystem();
		return _instance;
	}
	
	/**
	 * Returns {@code true} if passed-in {@code folder} is a valid directory 
	 * on filesystem.
	 * 
	 * @param folder A fully qualified path
	 */
	public function isDirectory( folder : String ) : Boolean
	{
		if( !folder ) return false;
		if( folder == '/' ) return true;
		
		return Boolean( ExternalInterface.call( 
			isDirectoryMETHOD, 
			_buildCorrectDirectoryPath( folder ) 
		) );
	}
	
	/**
	 * Creates passed-in {@code folder} directory on filesystem.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * <p>If any part of the directory path does not exist it will be created.
	 * 
	 * @param folder A fully qualified path
	 */
	public function createDirectory( folder : String ) : Boolean
	{
		if( !folder || folder == '/' ) return false;
		
		_hasChanged = Boolean( ExternalInterface.call( 
			createDirectoryMETHOD, 
			_buildCorrectDirectoryPath( folder ) 
		) );
		return _hasChanged;
	}
	
	/**
	 * Removes passed-in {@code folder} directory from filesystem.
	 * 
	 * <p>All files / folders insides are also deleted.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param folder A fully qualified path
	 */
	public function deleteDirectory( folder : String ) : Boolean
	{
		if( !folder || folder == '/' ) return false;
		
		_hasChanged =  Boolean( ExternalInterface.call( 
			deleteDirectoryMETHOD, 
			_buildCorrectDirectoryPath( folder ) 
		) );
		return _hasChanged;
	}
	
	/**
	 * Renames passed-in {@code folder} directory with new passed-in 
	 * {@code newFolderName} name.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param folder A fully qualified path
	 * @param newFolderName new Folder name
	 */
	public function renameDirectory( folder : String, newName : String ) : Boolean
	{
		if( !folder || !newName || folder == '/' ) return false;
		
		var oldPath : String = _buildCorrectDirectoryPath( folder );
		var s : String = StringUtil.rightTrim( oldPath, '/' );
		var parent : String = s.substring( 0, s.lastIndexOf( '/' ) + 1);
		newName = parent + newName + '/';
		
		_hasChanged = Boolean( ExternalInterface.call( renameDirectoryMETHOD, oldPath, newName ) );
		return _hasChanged;
	}
	
	/**
	 * Returns {@code true} if passed-in {@code path} is a valid file 
	 * on filesystem.
	 * 
	 * @param path A fully qualified file path
	 */
	public function isFile( path : String ) : Boolean
	{
		if( !path || path == '/' ) return false;
		
		return Boolean( ExternalInterface.call( 
			isFileMETHOD, 
			_buildCorrectFilePath( path ) 
		) );
	}
	
	/**
	 * Renames passed-in {@code path} file with new passed-in 
	 * {@code newName} name.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param path A fully qualified file path
	 * @param newName A fully qualified file path
	 */
	public function renameFile( path : String, newName : String ) : Boolean
	{
		if( !path || !newName ) return false;
		
		var oldPath : String = _buildCorrectFilePath( path );
		var folder : String = path.substring( 0, path.lastIndexOf( '/' ) + 1);
		newName = folder + newName;
		
		_hasChanged = Boolean( ExternalInterface.call( renameFileMETHOD, oldPath, newName ) );
		return _hasChanged;
	}
	
	/**
	 * Removes passed-in {@code path} file from filesystem.
	 * 
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param path A fully qualified file path
	 */
	public function deleteFile( path : String ) : Boolean
	{
		if( !path || path == '/' ) return false;
		
		_hasChanged = Boolean( ExternalInterface.call( 
			deleteFileMETHOD, 
			_buildCorrectFilePath( path ) 
		) );
		return _hasChanged;
	}
	
	/** 
	 * Reads file text content.
	 * 
	 * @param path A full qualified filename
	 * 
	 * @return File content or {@code null} if application can't read file.
	 */
	public function readFile( path : String ) : String
	{
		if( !path || path == '/' ) return null;
		
		var result : String = String( ExternalInterface.call( 
			readFileMETHOD,
			_buildCorrectFilePath( path )
		) );
		
		FeverDebug.DEBUG( 'strong return ' + result );
		
		if( result == 'null' ) return null;
		else return result;
	}
	
	/**
	 * Writes text data into file.
	 * 
	 * @param path ( optional ) A fully qualified path to the file you want to write.<br />
	 * Default use application starting directory.
	 * @param data String to write in file
	 */
	public function writeToFile( data : String, path : String ) : Boolean
	{
		if( !path || path == '/' || data == undefined ) return false;
		
		return Boolean( ExternalInterface.call( 
			writeToFileMETHOD, 
			URLString.getProcess().encode( data ),
			_buildCorrectFilePath( path )
		) );
	}
	
	/**
	 * Appends text data into file.
	 * 
	 * @param path A fully qualified path to the file you want to write.<br />
	 * Default use application starting directory.
	 * @param data String to write in file
	 */
	public function appendToFile( data : String, path : String ) : Boolean
	{
		if( !path || path == '/' || data == undefined ) return false;
		
		return Boolean( ExternalInterface.call( 
			appendToFileMETHOD, 
			URLString.getProcess().encode( data ),
			_buildCorrectFilePath( path )
		) );
	}
	
	/**
	 * Returns all content of filesystem.
	 */
	public function getContent( folder : String ) : Object
	{
		_getServerFilSystem();
		
		if( !folder || folder == '/' ) return _fileSystem;
		else
		{
			folder = StringUtil.trim( folder, '/' );
			var a : Array = folder.split( '/' );
			var l : Number = a.length;
			var o : Object = _fileSystem;
			
			for( var i : Number = 0; i < l; i++ )
			{
				if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
				else return null;
			}
			
			return o;
		}
	}
	
	public function isAvailable() : Boolean
	{
		return _isAvailable;
	}
	
	/**
	 * Returns user "temporary" directory  from current system.
	 */
	public function getTempDirectory() : String 
	{
		return '.tmp';
	}

	/**
	 * Returns current application path from current system.
	 */
	public function getAppDirectory() : String 
	{
		return '/';
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor
	 */
	private function HTTPFilesystem()
	{
		var str : String = String( ExternalInterface.call( getContentMETHOD ) );
		_isAvailable = ( str != undefined &&  !StringUtil.contains( str, '404' ) );
		
		_hasChanged = true;
	}
	
	private function _getServerFilSystem() : Void
	{
		if( !_hasChanged ) return;
		
		var xmlString : String = String( ExternalInterface.call( getContentMETHOD ) );
		
		var xml : XML = new XML( );
		xml.ignoreWhite = true;
		xml.parseXML( xmlString );
		
		var deserializer : XMLToObjectDeserializer = new XMLToObjectDeserializer();
		_fileSystem = new Object();
		
		var xmlToObject : XMLToObject = new XMLToObject( null, deserializer );
		xmlToObject.deserializeData( xml.firstChild, _fileSystem );
		
		_hasChanged = false;
	}
	
	private function _buildCorrectDirectoryPath( path : String ) : String
	{
		path = StringUtil.leftTrim( path, '/' );
		
		return StringUtil.finishWithChar( path, '/', true );	
	}
	
	private function _buildCorrectFilePath( path : String ) : String
	{
		return StringUtil.trim( path, '/' );		
	}
}